#  $Id: fields.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
#  Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
#  
#  Permission to use, copy, modify, and distribute this software for any
#  purpose with or without fee is hereby granted, provided that the above
#  copyright notice and this permission notice appear in all copies.
# 
#  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
#  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
#  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

__version__ = "$Revision: 7557b5d4d82b $"
__author__ = "$Author: pgurumur $"

from django import forms
from django.forms import widgets

from djanet import utils
from djanet.lib import ip, stdlib

"""
class NumberChoiceField(forms.IntegerField):
   widget = forms.NumberSpinnerInput

   def __init__(self, *Args, **keywords):
      self._log = utils.loghandle(stdlib.my_name(self))
      self._delta = 0
      self._max = 0
      self._min = 0
      self._initial = 0
      self._mesg = None

      if "delta" in keywords:
         try:
            self._delta = int(keywords['delta'])
         except ValueError, message:
            raise util.ValidationError, message
         finally:
            del keywords['delta']

         if self._delta <= 0:
            raise util.ValidationError, "delta value cannot be <= zero"

      if "default" in keywords:
         try:
            self._initial = int(keywords['default'])
         except ValueError, message:
            raise util.ValidationError, message
         finally:
            del keywords['default']

      if "max_value" in keywords:
         try:
            self._max = int(keywords["max_value"])
         except ValueError, message:
            raise util.ValidationError, message

      if "min_value" in keywords:
         try:
            self._min = int(keywords["min_value"])
         except ValueError, message:
            raise util.ValidationError, message

      if "help_text" in keywords:
         self._mesg = keywords['help_text']

      super(NumberChoiceField, self).__init__(*Args, **keywords)

   def widget_attrs(self, widget):
      retval = {}
      retval['smallDelta'] = self._delta
      retval['value'] = self._initial
      if self._mesg:
         retval['promptMessage'] = self._mesg

      retval['constraints'] = { 'min': self._min, 'max': self._max,
            'places': 0 }
      return retval

class IPAddressField(NetworkAddress):
   def widget_attrs(self, widget):
      retval = {}
      retval['regExpGen'] = "dojox.validate.regexp.ipAddress"
      if self._value:
         retval['value'] = self._value

      if self._mesg:
         retval['promptMessage'] = self._mesg

      retval['constraints'] = {
            'allowIPv6' : 'false', 'allowHybrid' : 'false' }

      return retval

class IPv6AddressField(NetworkAddress):
   def widget_attrs(self, widget):
      retval = {}
      retval['regExpGen'] = "dojox.validate.regexp.ipAddress"
      retval['uppercase'] = "true"
      if self._value:
         retval['value'] = self._value

      if self._mesg:
         retval['promptMessage'] = self._mesg

      retval['constraints'] = {
            'allowDottedDecimal' : "false", 'allowDottedHex' : "false",
            'allowDottedOctal' : "false" }

      return retval

class Select(forms.DojoWidgetMixin, widgets.Select):
   dojo_type = 'dijit.form.FilteringSelect'
   valid_extra_attrs = [
         'required',
         'help_text',
         ]

"""

class NetworkAddressField(forms.CharField):
   def __init__(self, *Args, **keywords):
      self._log = utils.loghandle(stdlib.my_name(self))
      self._mesg = None
      self._version = 0

      if "help_text" in keywords:
         self._mesg = keywords['help_text']

      if "max_digits" in keywords:
         del keywords["max_digits"]

      if "decimal_places" in keywords:
         del keywords["decimal_places"]

      keywords['max_length'] = 39
      super(NetworkAddressField, self).__init__(*Args, **keywords)

   def clean(self, value):
      value = super(NetworkAddressField, self).clean(value)
      if value:
         if self._version:
            try:
               temp = ip.ip(value)
            except exception.IPError, message:
               raise forms.ValidationError, message
      else:
         raise forms.ValidationError, "no value defined!"

      return value
